import config from './config'
import axios from 'axios'
import md0 from './md0/md0'

async function request (url) {
  let {data} = await axios.get(url)
  return data
}

/**
 * 加载目录下的所有东西
 * @param url
 */
async function getEntries (url, root, assets) {
  let data = await request(url)

  let temp = []
  for (let i = 0; i < data.length; i++) {
    let entry = data[i]

    // ignore items not in root directory
    if (root && entry.path !== root && entry.path.indexOf(root + '/') !== 0) {
      continue
    }

    // ignore the assets folder
    if (entry.path === assets || entry.path.indexOf(assets + '/') === 0) {
      continue
    }

    entry.path = entry.path.replace(new RegExp(`^${config.root}/`), '')

    if (entry.type !== 'dir') {
      temp.push(entry)
      continue
    }

    entry.children = await getEntries(entry.url)
    if (entry.path === root) {
      temp = entry.children
    } else {
      temp.push(entry)
    }
  }

  return temp
}

/**
 * 加载目录树信息
 */
function tree () {
  return getEntries(config.url.replace('{path}', ''), config.root, config.assets)
}

function parseContent (data) {
  // file(object) or dir(array)
  if (Array.isArray(data)) {
    // filter the file items
    // ignore invisible items
    return data.filter(item => {
      item.parent = item.path.replace(new RegExp(`^${config.root}(/.+?)*/${item.name.replace('.', '\\.')}`), '$1')
      item.path = item.path.replace(new RegExp(`^${config.root}/`), '')
      return item.type === 'file' && item.name[0] !== '.'
    })
  }

  // 暂时仅支持base64编码
  if (data.encoding !== 'base64') {
    console.error('Non-base64 encoded data is not supported yet')
    return data
  }
  // decode
  data.content = Buffer.from(data.content.replace(/\n/g, '').replace(/\s/g, '+'), 'base64').toString()

  // render markdown
  if (/\.md$/i.test(data.name)) {
    data.content = md0(data.content, {
      titleAnchor: false
    })
  } else {
    // in order to present the raw content
    // wrap with <pre>
    data.content = `<pre class="content-raw">${data.content.replace(/</g, '&lt;')}</pre>`
  }

  // category
  let reg = new RegExp(`^${config.root}(/.+?)*/${data.name.replace('.', '\\.')}`)
  data.parent = reg.test(data.path) ? data.path.replace(reg, '$1') : ''

  // edit
  data.edit_url = data.html_url.replace('/blob/', '/edit/')

  return data
}

async function file (path) {
  if (!path) {
    return {}
  }
  if (/^\/?readme\.md$/i.test(path)) {
    return readme()
  }
  let data = await request(config.url.replace('{path}', config.root + '/' + path))

  return parseContent(data)
}

async function readme () {
  let data = await request(config.readme)
  return parseContent(data)
}

export default {
  tree,
  file,
  root: config.root
}
